/**
 * MIT License
 * 
 * Copyright (c) 2024 - present @ ebraid
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <kernel/bus.h>
#include <kernel/syslog.h>
#include <lib/eb_string.h>
#include <list.h>


bool bus_is_registered(struct bus_type *bus)
{
    if(kobj_find_by_name(NULL, bus->name) == NULL) {
        return false;
    }
    else {
        return true;
    }
}


const char *bus_get_name(struct bus_type *bus)
{
    if(bus && bus->kobj.name) {
        return bus->kobj.name;
    }

    return NULL;
}


int bus_register(struct bus_type *bus)
{
    if(bus == NULL) {
        return EB_ERR;
    }

    if(bus->name == NULL) {
        SYSLOG_ERROR("bus's name is not set");
        return EB_ERR;
    }

    if(bus_is_registered(bus)) {
        SYSLOG_ERROR("%s bus is registered", bus->name);
        return EB_ERR;
    }

    kobj_init(&bus->kobj, bus->name, NULL);
    if(!kobj_add(NULL, &bus->kobj)){
        return EB_ERR;
    }

    kobj_init(&bus->dev_kobj, "devices", NULL);
    if(!kobj_add(&bus->kobj, &bus->dev_kobj)){
        return EB_ERR;
    }

    kobj_init(&bus->drv_kobj, "drivers", NULL);
    if(!kobj_add(&bus->kobj, &bus->drv_kobj)){
        return EB_ERR;
    }

    return EB_OK;
}


void bus_unregister(struct bus_type *bus)
{
    if(bus_is_registered(bus)) {
        kobj_remove_self(&bus->kobj);
        return;
    }

    SYSLOG_WARN("bus is not register, so it can not delete");
}


int bus_attach_match_id(struct match_id *table, const char *compatible)
{
    for(int i = 0; ; i++) {
        if(*table[i].compatible && compatible) {
            if(eb_strcmp(table[i].compatible, compatible) == 0) {
                return i;
            }
        }
        else {
            return -1;
        }
    }

    return -1;
}


int bus_attach_match_name(const char* dev_name, const char* drv_name)
{
    return eb_strcmp(dev_name, drv_name) == 0 ? 0 : -1;
}
